/* Vejaa
 * Jan, 2009
 * 
 * Author: Rafael Carício - @rjcf
 */

var dj = require("./djangode");
var sys = require("sys");

Array.prototype.each = function (callback){
	for (var i=0;i<this.length;i++) callback(i, this[i]);
};

util = {
  urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g, 

  //  html sanitizer 
  toStaticHTML: function(inputHtml) {
    return inputHtml.replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;");
  }, 

  zeroPad: function (digits, n) {
    n = n.toString();
    while (n.length < digits) 
      n = '0' + n;
    return n;
  },

  timeString: function (date) {
    var minutes = date.getMinutes().toString();
    var hours = date.getHours().toString();
    return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
  },

  isBlank: function(text) {
    var blank = /^\s*$/;
    return (text.match(blank) !== null);
  }
};

var redirects = new function() {
	var reds = []; // {key:'',count:0,url:'',timestamp:new Date()}
	
	this.findRedirect = function(key, callback, errcallback) {
		reds.each(function(i,e){
			if (e.key == key) {
				callback(e);
			}
		});
		if (errcallback != null) errcallback();
	};
	
	this.addRedirect = function(url, callback) {
		var key = Math.floor(Math.random()*999).toString();
		var red = {'key':key,'count':0,'url':url,'timestamp':new Date()};
		reds.push(red);
		callback(red);
	};
	
	this.each = function(callback) {
		reds.each(function(i,e){
			callback(i,e);
		});
	};
};

// Testes
sys.puts("inicio dos testes...");
redirects.addRedirect('http://www.magicnumber.com.br/', function(re){
	redirects.findRedirect(re.key, function(re1) {
		sys.puts("key="+ re1.key);
		sys.puts("url="+ re1.url);
	});
});

var app = dj.makeApp([
		['^/$', function(req, res) {
			var html = [
	            '<h1>vejaa.in app</h1>', '<ul>'			            
            ];
			redirects.each(function(i,e) {
				html.push('<li><a href="http://localhost:8080/'+ e.key +'/">'+ e.url +'</a> (' + e.count + ')</li>');
			});
			html.push("</ul>");
			dj.respond(res, html.join(""));
		}],
		['^/(\\w+)/?$', function(req, res, key) {
			if (!util.isBlank(key)) {
			    redirects.findRedirect(key, 
			    	function(red) {
			    		dj.redirect(res, red.url);
			    		red.count += 1;
			    	}, function() {
			    		dj.respond(res, '<h1>the key '+ util.toStaticHTML(key) +' was not in vejaa.in database</h1>');
			    	});
			} else {
				dj.redirect(res, '/');
			}
		}],
]);
dj.serve(app, 8080);
